﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace Shop.Resources
{
    public static class DataGridViewExtensions
    {

        public static void ExportToExcel(this DataGridView dataGridView)
        {
            Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
            excelApp.Visible = false;
            Microsoft.Office.Interop.Excel.Workbook wb = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet ws = wb.ActiveSheet;

            for (int cols = 0; cols < dataGridView.Columns.Count; cols++)
            {
                ws.Cells[1, cols + 1] = dataGridView.Columns[cols].Name.ToString();
            }

            for (int i = 0; i < dataGridView.Rows.Count; i++)
            {
                for (int j = 0; j < dataGridView.Columns.Count; j++)
                {
                    if (dataGridView.Rows[i].Cells[j].Value == null)
                    {
                        continue;
                    }
                    ws.Cells[i + 2, j + 1] = dataGridView.Rows[i].Cells[j].Value.ToString();
                }
            }

            //wb.SaveAs("..\\..\\asd.xls",Microsoft.Office.Interop.Excel.XlFileFormat.xlXMLSpreadsheet);
            //wb.Close(true, @"C:\asd.xls");
            //excelApp.Save();
            //excelApp.SaveWorkspace();
            //ws.Activate();
            wb.Close();
            excelApp.Quit();
        }
    }
}
